package research.db;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

	public static final String MSSQL="MSSQL";
	public static final String ORACLE="ORACLE";
	
	private String path;
	private String currentSection = null;
	private String dbType = null;
//	private Map<String, Map<String, List<String>>> map = null;
	private DBMSSQLEntity dbmssqlEntity = null;
	private DBOracleEntity dbOracleEntity = null;

	public ReadFile(String dbType, String readFilePath) {
		this.dbType = dbType;
		this.path = readFilePath;
		if (MSSQL.equals(dbType)) {
			dbmssqlEntity = new DBMSSQLEntity();
		} else {
			dbOracleEntity = new DBOracleEntity();
		}
	}

	public DBBaseEntity ReadIni() {
//		map = new HashMap<String, Map<String, List<String>>>();
		String line = null;
		BufferedReader reader = null;
		try {

			reader = new BufferedReader(new FileReader(path));

			while ((line = reader.readLine()) != null) {
				parseLine(line);
			}

			if (MSSQL.equals(dbType)) {
				return dbmssqlEntity;
			} else {
				return dbOracleEntity;
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("IO Exception:" + e);
		}
		finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private void parseLine(String line) {
		line = line.trim();
		// 此部分为注释
		if (line.matches("^\\#.*$")) {
			return;
		} else if (line.matches("^\\[\\S+\\]$")) {
			// section
			currentSection = line.replaceFirst("^\\[(\\S+)\\]$", "$1");
		} else if (line.matches("^\\S+=.*$")) {
			// key ,value
			int i = line.indexOf("=");
			String key = line.substring(0, i).trim();
			String value = line.substring(i + 1).trim();

			if (MSSQL.equals(dbType) && MSSQL.equals(currentSection)) {
				if (key.equals("ServerName")) {
					dbmssqlEntity.setServerName(value);
				} else if (key.equals("Database")) {
					dbmssqlEntity.setDatabase(value);
				} else if (key.equals("User")) {
					dbmssqlEntity.setUser(value);
				} else {
					dbmssqlEntity.setPwd(value);
				}
			} else if (ORACLE.equals(dbType) && ORACLE.equals(currentSection)) {
				if (key.equals("ServerName")) {
					dbOracleEntity.setServerName(value);
				} else if (key.equals("User")) {
					dbOracleEntity.setUser(value);
				} else {
					dbOracleEntity.setPwd(value);
				}
			}
		}
	}
}
